﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Collections;
using System.Reflection;
using System.Data;

namespace CustomerMaterialNoMonitor_14
{
    /// <summary>
    /// 基本工具，放置不需要访问数据库的操作
    /// </summary>
    public static class GeneralTools
    {
        /// <summary>
        /// 默认服务器地址
        /// </summary>
        public static string strServer = "192.168.1.1";
        //public static string strServer = ".";

        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="strDBName">数据库名称</param>
        /// <returns>数据库连接字符串</returns>
        public static string GetConnectionString(string strDBName)
        {
            return GetConnectionString(strServer, strDBName);
        }

        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="strHost">主机地址</param>
        /// <param name="strDBName">数据库名称</param>
        /// <returns>数据库连接字符串</returns>
        public static string GetConnectionString(string strHost,string strDBName)
        {
            string strTmpConncetionString = "Data Source=@Server;Initial Catalog=@DBName;Persist Security Info=True;User ID=sa;Password=856518armyman";
            return strTmpConncetionString.Replace ("@Server",strHost )
                                                              .Replace ("@DBName",strDBName );
        }

        /// <summary>
        /// 将对象转换为字符串
        /// </summary>
        /// <param name="tmpobj">要转换的对象</param>
        /// <param name="strdefault">转换错误时的默认值</param>
        /// <returns>字符串结果</returns>
        public static string GetString(object tmpobj,string strdefault)
        {
            try
            {
                return tmpobj.ToString().Trim ();
            }
            catch
            {
                return strdefault;
            }
        }

        /// <summary>
        /// 将对象转换为整型
        /// </summary>
        /// <param name="tmpobj">要转换的对象</param>
        /// <param name="idefault">转换错误时的默认值</param>
        /// <returns>整型结果</returns>
        public static int GetInt(object tmpobj,int idefault)
        {
            try
            {
                return Convert.ToInt32(tmpobj);
            }
            catch
            {
                return idefault;
            }
        }

        /// <summary>
        /// 将对象转换为浮点数
        /// </summary>
        /// <param name="tmpobj">要转换的对象</param>
        /// <param name="ddefault">转换错误时的默认值</param>
        /// <returns>浮点结果</returns>
        public static double GetDouble(object tmpobj,double ddefault)
        {
            try
            {
                return Convert.ToDouble(tmpobj);
            }
            catch
            {
                return ddefault;
            }
        }

        /// <summary>
        /// 将对象转换为布尔型
        /// </summary>
        /// <param name="tmpobj">要转换的对象</param>
        /// <param name="bdefault">转换错误时的默认值</param>
        /// <returns>布尔结果</returns>
        public static bool GetBoolean(object tmpobj,bool bdefault)
        {
            try
            {
                return Convert.ToBoolean(tmpobj);
            }
            catch
            {
                return bdefault;
            }
        }

        /// <summary>
        /// 判断字符是否为汉字
        /// </summary>
        /// <param name="tmpc">需判断的字符</param>
        /// <returns>是否为汉字</returns>
        public static bool IsChineseChar(char tmpc)
        {
            if ((int)tmpc > 127)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 计算字符串长度，中文字符为2
        /// </summary>
        /// <param name="strTmp">要计算的字符串</param>
        /// <returns>长度</returns>
        public static int GetChineseTextLength(string strTmp)
        {
            int iLength=0;
            for(int i=0;i<strTmp .Length ;i++)
            {
                if (IsChineseChar (strTmp [i]))
                {
                    iLength +=2;
                }
                else 
                {
                    iLength +=1;
                }
            }
            return iLength ;
        }

        /// <summary>
        /// 显示消息提示框
        /// </summary>
        /// <param name="strMsg">消息</param>
        public static void ShowInfoMsg(string strMsg)
        {
            MessageBox.Show(strMsg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 显示警告提示框
        /// </summary>
        /// <param name="strMsg">警告信息</param>
        public static void ShowWarningMsg(string strMsg)
        {
            MessageBox.Show(strMsg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning );
        }

        /// <summary>
        /// 显示错误提示框
        /// </summary>
        /// <param name="strMsg">错误信息</param>
        public static void ShowErrorMsg(string strMsg)
        {
            MessageBox.Show(strMsg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 获取字符串的MD5值
        /// </summary>
        /// <param name="strTmp">要计算MD5的字符串</param>
        /// <returns>MD5值</returns>
        public static string GetMD5(string strTmp)
        {
            MD5 m = new MD5CryptoServiceProvider();
            byte[] b = Encoding.Default.GetBytes(strTmp);
            byte[] result = m.ComputeHash(b);
            return BitConverter.ToString(result).Replace("-", "");
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="strMsg">要写入的信息</param>
        public static void WriteToLogFile(string strMsg)
        {
            string strLogFileName = Application.StartupPath + "\\log.txt";
            try
            {
                StreamWriter sw = File.AppendText(strLogFileName);
                sw.WriteLine("["+DateTime .Now .ToString ()+"]"+ strMsg);
                sw.Close();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        /// <summary>
        /// 为INI文件中指定节点指定项获取字符串
        /// </summary>
        /// <param name="lpAppName">要查找的节点名称</param>
        /// <param name="lpKeyName">要获取的项名</param>
        /// <param name="lpDefault">指定的项没有找到时返回的默认值</param>
        /// <param name="lpReturnedString">用于装载返回值的字符串缓冲区</param>
        /// <param name="nSize">缓冲区的最大字符数量</param>
        /// <param name="lpFileName">INI文件名</param>
        /// <returns>复制到缓冲区的字节数量，不包括NULL终止字符</returns>
        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        /// <summary>
        /// 向INI文件中指定节点指定项写入字符
        /// </summary>
        /// <param name="lpApplicationName">要写入的节点名称</param>
        /// <param name="lpKeyName">要写入的项名</param>
        /// <param name="lpString">要写入的值</param>
        /// <param name="lpFileName">INI文件名</param>
        /// <returns>非零表示写入成功，零表示写入失败</returns>
        [DllImport("kernel32")]
        public static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);

        /// <summary>    
        /// 将泛型集合类转换成DataTable    
        /// </summary>    
        /// <typeparam name="T">集合项类型</typeparam>    
        /// <param name="list">集合</param>    
        /// <param name="propertyName">需要返回的列的列名</param>    
        /// <returns>数据集(表)</returns>    
        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
        {
            List<string> propertyNameList = new List<string>();
            if (propertyName != null)
                propertyNameList.AddRange(propertyName);
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (propertyNameList.Count == 0)
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else
                    {
                        if (propertyNameList.Contains(pi.Name))
                            result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (propertyNameList.Count == 0)
                        {
                            object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                            {
                                object obj = pi.GetValue(list[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
    }
}
